package com.gulimall.ware.service.impl;

import com.gulimall.common.utils.R;
import com.gulimall.ware.feign.ProductFeignService;
import com.gulimall.ware.to.product.SkuHasStockTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;

import com.gulimall.ware.dao.WareSkuDao;
import com.gulimall.ware.entity.WareSkuEntity;
import com.gulimall.ware.service.WareSkuService;


@Service("wareSkuService")
public class WareSkuServiceImpl extends ServiceImpl<WareSkuDao, WareSkuEntity> implements WareSkuService {
    @Autowired
    private ProductFeignService productFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<>();

        String skuId = (String) params.get("skuId");
        if (StringUtils.isNotEmpty(skuId)) {
            queryWrapper.eq("sku_id", skuId);
        }
        String wareId = (String) params.get("wareId");
        if (StringUtils.isNotEmpty(wareId)) {
            queryWrapper.eq("ware_id", wareId);
        }

        IPage<WareSkuEntity> page = this.page(
                new Query<WareSkuEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    /**
     * 添加库存接口
     *
     * @param skuId
     * @param wareId
     * @param skuNum
     */
    @Override
    public void addStock(Long skuId, Long wareId, Integer skuNum) {
        try {
            QueryWrapper<WareSkuEntity> queryWrapper = new QueryWrapper<WareSkuEntity>() {{
                eq("sku_id", skuId).eq("ware_id", wareId);
            }};
            List<WareSkuEntity> wareSkuEntityList = this.list(queryWrapper);

            //判断之前是否存在库存，不存在直接添加，存在则进行修改
            if (wareSkuEntityList.isEmpty()) {
                WareSkuEntity wareSkuEntity = new WareSkuEntity();
                R info = productFeignService.info(skuId);
                Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
                wareSkuEntity.setSkuId(skuId);
                wareSkuEntity.setSkuName((String) skuInfo.get("skuName"));
                wareSkuEntity.setWareId(wareId);
                wareSkuEntity.setStock(skuNum);
                this.save(wareSkuEntity);
            }
        } catch (Exception e) {
            this.addStock(skuId, wareId, skuNum);
        }
    }

    /**
     * 商品库存新增功能接口
     *
     * @param wareSku
     * @return
     */
    @Override
    public R saveDetail(WareSkuEntity wareSku) {
        //判断skuId是否已经存在当前库存列表中
        int count = this.count(new QueryWrapper<WareSkuEntity>() {{
            eq("sku_id", wareSku.getSkuId()).eq("ware_id", wareSku.getWareId());
        }});
        if (count > 0) {
            return R.error("当前skuId已经存在该仓库中!");
        }

        try {
            //调用远程接口 根据skuId获取sku详细信息
            R info = productFeignService.info(wareSku.getSkuId());
            Map<String, Object> skuInfo = (Map<String, Object>) info.get("skuInfo");
            wareSku.setSkuName((String) skuInfo.get("skuName"));
            this.save(wareSku);
            return R.ok();
        } catch (Exception e) {
            return R.error("skuId不存在");
        }
    }

    /**
     * 查询sku是否有库存
     *
     * @param skuIds
     * @return
     */
    @Override
    public List<SkuHasStockTo> getSkusHasStock(List<Long> skuIds) {
        List<SkuHasStockTo> collect = skuIds.stream().map(item -> {
            SkuHasStockTo skuHasStockTo = new SkuHasStockTo();
            //查询当前sku的总库存量（总库存 = 库存 - 锁定库存）
            //SELECT SUM (stock-stock_locked) FROM wms_ware_sku WHERE sku_id = #{skuId}
            //避免在查询库存时有返回null的类型导致报错，这里使用long的包装类接收
            Long count = baseMapper.getSkuStockBySkuId(item);
            skuHasStockTo.setSkuId(item);
            //当查询到的库存数量大于0为TRUE
            skuHasStockTo.setHasStock(count != null && count > 0);
            return skuHasStockTo;
        }).collect(Collectors.toList());

        return collect;
    }
}